package com.lisx.module_time_block.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.lib_data.constants.EventBusConstants;
import com.fenghuajueli.lib_data.entity.db.DayPlanDbEntity;
import com.fenghuajueli.lib_data.entity.eventbus.EventEntity;
import com.fenghuajueli.libbasecoreui.manager.TimeBlockManager;
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModelFragment2;
import com.lisx.module_time_block.activity.MonthBlockDetailsActivity;
import com.lisx.module_time_block.activity.NewBlockActivity;
import com.lisx.module_time_block.activity.WeekBlockDetailsActivity;
import com.lisx.module_time_block.adapter.TimeBlockItemAdapter;
import com.lisx.module_time_block.bean.NewBlockIconBean;
import com.lisx.module_time_block.databinding.FragmentTimeBlockItemBinding;
import com.lisx.module_time_block.dialogfragment.DakaDialogFragment;
import com.fenghuajueli.libbasecoreui.dialogfragment.MessageDialogFragment;
import com.lisx.module_time_block.utils.TimeUtils;
import com.lisx.module_time_block.viewmodel.TimeBlockItemViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.TimeZone;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class TimeBlockItemFragment extends BaseViewModelFragment2<TimeBlockItemViewModel, FragmentTimeBlockItemBinding> {

    private TimeBlockItemAdapter adapter;
    private int index;
    private MessageDialogFragment messageDialogFragment;

    @Override
    protected TimeBlockItemViewModel createViewModel() {
        return new TimeBlockItemViewModel();
    }

    @Override
    protected FragmentTimeBlockItemBinding createViewBinding() {
        return FragmentTimeBlockItemBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView(View containerView) {
        EventBus.getDefault().register(this);

        Bundle arguments = getArguments();
        if (arguments != null) {
            index = arguments.getInt("index", 0);
        }

        binding.ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), NewBlockActivity.class);
                intent.putExtra("index", index);
                startActivity(intent);
            }
        });

        binding.recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new TimeBlockItemAdapter(getContext(), NewBlockIconBean.getNewBlockBigIconData());
        binding.recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new TimeBlockItemAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(int position, DayPlanDbEntity entity) {
                if (index == 4) {
                    Intent intent = new Intent(getActivity(), WeekBlockDetailsActivity.class);
                    intent.putExtra("position",position);
                    startActivity(intent);
                } else if (index == 5) {
                    Intent intent = new Intent(getActivity(), MonthBlockDetailsActivity.class);
                    intent.putExtra("position",position);
                    startActivity(intent);
                } else {
                    DakaDialogFragment dakaDialogFragment = new DakaDialogFragment();
                    dakaDialogFragment.setData(entity);
                    dakaDialogFragment.setOnDakaListener(new DakaDialogFragment.OnDakaListener() {
                        @Override
                        public void onDaka(String msg) {
                            daka(entity, msg);
                        }
                    });
                    dakaDialogFragment.show(getChildFragmentManager());
                }
            }

            @Override
            public void onItemLongClick(DayPlanDbEntity entity) {
                if (messageDialogFragment == null) {
                    messageDialogFragment = new MessageDialogFragment();
                }
                messageDialogFragment.setMessageContent("确认删除此规划?");
                messageDialogFragment.setMessageDialogListener(new MessageDialogFragment.MessageDialogListener() {
                    @Override
                    public void onRightClick() {
                        delete(entity);
                    }

                    @Override
                    public void onLeftClick() {

                    }
                });
                messageDialogFragment.show(getChildFragmentManager());
            }
        });

        setData();
    }

    private void daka(DayPlanDbEntity entity, String msg) {
        long dakaTime = entity.getDaka_time();
        long currentTime = System.currentTimeMillis();
        if (!TimeUtils.isSameDay(dakaTime, currentTime, TimeZone.getDefault())) {
            if (TextUtils.isEmpty(msg)) {
                ToastUtils.showShort("请输入内容!");
                return;
            }
            update(entity, msg);
        } else {
            ToastUtils.showShort("今天已经打过卡了,明天再来噢!");
        }
    }

    private void update(DayPlanDbEntity entity, String msg) {
        entity.setDaka_count(entity.getDaka_count() + 1);
        entity.setDaka_time(System.currentTimeMillis());
        entity.setMsg(msg);
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Boolean> emitter) throws Exception {
                TimeBlockManager.getInstance().updateDayPlan(entity);
                emitter.onNext(true);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Boolean aBoolean) {
                        EventBus.getDefault().post(new EventEntity(EventBusConstants.SAVE_PLAN));
                        ToastUtils.showShort("打卡成功");
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ToastUtils.showShort("打卡失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    private void delete(DayPlanDbEntity entity) {
        Observable.create(new ObservableOnSubscribe<List<DayPlanDbEntity>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<DayPlanDbEntity>> emitter) throws Exception {
                List<DayPlanDbEntity> dayPlanData = TimeBlockManager.getInstance().deleteDayPlan(entity.getCreate_time(), index);
                emitter.onNext(dayPlanData);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<List<DayPlanDbEntity>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull List<DayPlanDbEntity> dayPlanDbEntities) {
                        if (dayPlanDbEntities != null) {
                            adapter.setData(dayPlanDbEntities);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void initData() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(EventEntity eventBusEntity) {
        if (eventBusEntity.getCode() == EventBusConstants.SAVE_PLAN) {
            setData();
        }

    }

    private void setData() {
        Observable.create(new ObservableOnSubscribe<List<DayPlanDbEntity>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<DayPlanDbEntity>> emitter) throws Exception {
                List<DayPlanDbEntity> dayPlanData = TimeBlockManager.getInstance().getDayPlanData(index);
                emitter.onNext(dayPlanData);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<List<DayPlanDbEntity>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull List<DayPlanDbEntity> dayPlanDbEntities) {
                        if (dayPlanDbEntities != null) {
                            adapter.setData(dayPlanDbEntities);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
